﻿using System.Collections.Generic;
using System.Linq;
using Poker;

namespace Games
{
    public class GameRule
    {
        public bool IsAceHigh(DeckOfCard pokerCards) => pokerCards.Any(x => x.Suit == PokerSuit.Ace);
        /// <summary>
        /// 两张相同, 对子
        /// </summary>
        public bool IsPair(DeckOfCard pokerCards) => pokerCards.Select(x => x.Suit).Distinct().Count() < pokerCards.Count;
        /// <summary>
        /// 同花
        /// </summary>
        public bool IsSuited(DeckOfCard pokerCards) => pokerCards.Select(x => x.Color).Distinct().Count() == 1;
        /// <summary>
        /// 顺子
        /// </summary>
        public bool IsStraight(DeckOfCard pokerCards) => (pokerCards[^1].Suit == PokerSuit.Ace) ? (pokerCards[0].Suit == PokerSuit.Two && IsFollowings(pokerCards.Take(pokerCards.Count - 1).ToList())) : IsFollowings(pokerCards);
        /// <summary>
        /// 同花顺
        /// </summary>
        public bool IsSuitedAndStraight(DeckOfCard pokerCards) => IsSuited(pokerCards) && IsStraight(pokerCards);
        /// <summary>
        /// 三张相同, 豹子
        /// </summary>
        public bool IsSet(DeckOfCard pokerCards) => pokerCards.Select(x => x.Suit).Distinct().Count() == 1;
        /// <summary>
        /// 返回规则中最大的牌型
        /// </summary>
        /// <param name="pokerCards"></param>
        /// <returns></returns>
        public virtual KindOfCards GetKindOfCards(DeckOfCard pokerCards)
        {
            if (IsSet(pokerCards))
            {
                return KindOfCards.Set;
            }

            if (IsSuitedAndStraight(pokerCards))
            {
                return KindOfCards.SuitedAndStraight;
            }

            if (IsStraight(pokerCards))
            {
                return KindOfCards.Straight;
            }

            if (IsSuited(pokerCards))
            {
                return KindOfCards.Suited;
            }

            if (IsPair(pokerCards))
            {
                return KindOfCards.Pair;
            }

            if (IsAceHigh(pokerCards))
            {
                return KindOfCards.AceHigh;
            }

            return KindOfCards.Offsuit;
        }

        /// <summary>
        /// 判断牌面是否是连续的
        /// </summary>
        /// <param name="pokerCards"></param>
        /// <returns></returns>
        private bool IsFollowings(List<PokerCard> pokerCards)
        {
            var index = 0;
            bool result;
            do
            {
                result = pokerCards[index].Suit + 1 == pokerCards[index++].Suit;
            } while (result && index < pokerCards.Count);

            return result;
        }
    }
}
